﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Dnf.Tools.Sugar
{
    public static class StringHelpers
    {
        //private static List<string> VideoLinks = new List<string>();


        public static string ConvertStringToHtml(string text,
                                                 ConvertStringToHtmlOptions options)
        {
            //VideoLinks.Clear();
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }

            string _html = text;
            if (options.ReplaceNewLines)
                _html = text.Replace("\r\n", "<br/>");

            if (options.LinkUrls)
                _html = LinkUrls(_html, options.ShortenUrls, options.ParseYoutubeLinks,
                                 options.LinkTemplate, options.YouTubeLinkTemplate,
                                 options.VimeoLinkTemplate);

            if (options.LinkTwitterUsername)
                _html = SocialMediaHelpers.ParseTwitterUserNames(_html, options.TwitterUsernameLinkTemplate);

            if (options.LinkTwitterHashes)
                _html = SocialMediaHelpers.ParseTwitterSearchTerms(_html, options.TwitterHashLinkTemplate);

            return _html;
        }

        private static string LinkUrls(string _html, bool shortenLinks, bool parseYoutubeLinks,
                                       string linkTemplate, string youtubeLinkTemplate, string vimeoLinkTemplate)
        {
            var UrlExpression =
                new Regex(
                    @"((http|ftp|https):\/\/)?[\w\-_]+(\.[a-zA-Z\-_]+[a-zA-Z\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#\*]*[\w\-\@?^=%&amp;/~\+#\*])?",
                    RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (shortenLinks)
            {
                _html = UrlExpression.Replace(_html, match =>
                                                     SocialMediaHelpers.IsYouTubeLink(match.ToString())
                                                         ?
                                                             match.ToString()
                                                         :
                                                             BitlyApi.ShortenUrl(match.ToString()).ShortUrl);
            }


            if (parseYoutubeLinks)
            {
                _html = UrlExpression.Replace(_html,
                                              match =>
                                              (!string.IsNullOrEmpty(youtubeLinkTemplate) &&
                                               SocialMediaHelpers.IsYouTubeLink(match.ToString()))
                                                  ?
                                                      string.Format(
                                                          youtubeLinkTemplate,
                                                          match.ToString().ToLower().StartsWith("http")
                                                              ? match.ToString()
                                                              : string.Format("http://{0}", match.ToString()),
                                                          new Regex("v=(((.*)(?=[&/]))|(.*))").Match(match.ToString()).
                                                              ToString()
                                                              .Substring(2)).Replace("watch?v=", "v/")
                                                          .Replace("w/?v=", "v/")
                                                  :
                                                      (!string.IsNullOrEmpty(vimeoLinkTemplate) &&
                                                       SocialMediaHelpers.IsVimeoLink(match.ToString()))
                                                          ?
                                                              string.Format(
                                                                  vimeoLinkTemplate,
                                                                  match.ToString().Split('/').Last()
                                                                  )
                                                          :
                                                              string.Format(linkTemplate,
                                                                            match.ToString().ToLower().StartsWith("http")
                                                                                ? match.ToString()
                                                                                : string.Format("http://{0}",
                                                                                                match.ToString()),
                                                                            match.ToString()));
                //if (!string.IsNullOrEmpty(vimeoLinkTemplate))
                //{
                //    _html = UrlExpression.Replace(_html,
                //                                  match =>
                //                                  SocialMediaHelpers.IsVimeoLink(match.ToString())
                //                                      ?
                //                                          string.Format(
                //                                              vimeoLinkTemplate,
                //                                              match.ToString().Split('/').Last()
                //                                              )
                //                                      :
                //                                          string.Format(linkTemplate,
                //                                                        match.ToString().ToLower().StartsWith("http")
                //                                                            ? match.ToString()
                //                                                            : string.Format("http://{0}",
                //                                                                            match.ToString()),
                //                                                        match.ToString()));
                //}
            }
            else
            {
                _html = UrlExpression.Replace(_html, match =>
                                                     string.Format(linkTemplate,
                                                                   match.ToString().ToLower().StartsWith("http")
                                                                       ? match.ToString()
                                                                       : string.Format("http://{0}", match.ToString()),
                                                                   match.ToString()));
            }
            return _html;
        }

        public class ConvertStringToHtmlOptions
        {
            public ConvertStringToHtmlOptions()
            {
                LinkTemplate = "<a href='{0}' target='_blank'>{1}</a>";
                YouTubeLinkTemplate =
                    "<a class='vidlink' href='{0}' target='_blank'><img src='http://img.youtube.com/vi/{1}/1.jpg' class='vidthumbnail'></a>";
                TwitterUsernameLinkTemplate =
                    "{1}<a href='http://twitter.com/{0}' class='twitterusername' target='_blank'>@{0}</a>";
                TwitterHashLinkTemplate = "{1}<a href='http://search.twitter.com/search?q={0}' target='_blank'>#{0}</a>";
            }

            public bool ShortenUrls { get; set; }

            public bool LinkUrls { get; set; }

            public bool ParseYoutubeLinks { get; set; }

            public bool LinkTwitterUsername { get; set; }

            public bool LinkTwitterHashes { get; set; }

            public bool ReplaceNewLines { get; set; }

            public string LinkTemplate { get; set; }
            public string YouTubeLinkTemplate { get; set; }
            public string VimeoLinkTemplate { get; set; }

            public string TwitterUsernameLinkTemplate { get; set; }
            public string TwitterHashLinkTemplate { get; set; }
        }
    }
}